package com.dragon.loan.service;

import com.dragon.common.entity.search.Searchable;
import com.dragon.common.repository.mybatis.paginator.domain.Order;
import com.dragon.common.repository.mybatis.paginator.domain.PageBounds;
import com.dragon.common.service.BaseService;
import com.dragon.loan.entity.AcLoanApplyLinkman;
import com.dragon.loan.repository.AcLoanApplyLinkmanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AcLoanApplyLinkmanServiceImpl extends BaseService<AcLoanApplyLinkman, Long> implements AcLoanApplyLinkmanService{

	@Autowired
	private AcLoanApplyLinkmanRepository loanApplyLinkmanRepository;
	
	public int deleteLinkman(String loanId,String linkmanId){
		if(!StringUtils.hasText(loanId) && !StringUtils.hasText(linkmanId)){
			return 0;
		}
		return loanApplyLinkmanRepository.deleteLinkman(loanId, linkmanId);
	}
	
	public int updateByLinkmanId(AcLoanApplyLinkman acLoanApplyLinkman){
		return loanApplyLinkmanRepository.updateByLinkmanId(acLoanApplyLinkman);
	}
	
	public List<AcLoanApplyLinkman> selectListBySearchable(Searchable searchable){
		return loanApplyLinkmanRepository.selectListBySearchable(searchable);
	}
	
	public Long queryLinkmanCount(String loanId, String linkmanMobile) {
		if (!StringUtils.hasText(loanId) || !StringUtils.hasText(linkmanMobile)) {
			throw new RuntimeException("贷款编号和联系人手机号码必输");
		}
		Searchable searchable = Searchable.newSearchable();
		searchable.addSearchParam("loanId_eq", loanId);
		searchable.addSearchParam("linkmanMobile_eq", linkmanMobile);
		return selectCount(searchable);
	}
	
	public void save(String loanId,List<AcLoanApplyLinkman> acLoanApplyLinkmans) {
		for (AcLoanApplyLinkman acLoanApplyLinkman : acLoanApplyLinkmans) {
			acLoanApplyLinkman.setLoanId(loanId);
			acLoanApplyLinkman.setCreateTime(new Date());
			acLoanApplyLinkman.setUpdateTime(new Date());
			save(acLoanApplyLinkman);
		}
	}
	
	public List<AcLoanApplyLinkman> queryLinkmanList(String loanId) {
		if (!StringUtils.hasText(loanId)) {
			return null;
		}
		Searchable searchable = Searchable.newSearchable();
		searchable.addSearchParam("loanId_eq", loanId);
		List<Order> orderList = new ArrayList<Order>();
		Order id = Order.create("id", "desc");
		orderList.add(id);
		return selectList(searchable, new PageBounds(orderList));
	}

	public AcLoanApplyLinkman queryLinkman(String linkmanId) {
		if (!StringUtils.hasText(linkmanId)) {
			return null;
		}
		Searchable searchable = Searchable.newSearchable();
		searchable.addSearchParam("linkmanId_eq", linkmanId);
		return selectBySearchable(searchable);
	}
}
